package com.xiaoxing.yunshu.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.yunshu.R;
import com.xiaoxing.yunshu.di.component.DaggerOrdersYiWanChengComponent;
import com.xiaoxing.yunshu.di.module.OrdersYiWanChengModule;
import com.xiaoxing.yunshu.mvp.contract.OrdersYiWanChengContract;
import com.xiaoxing.yunshu.mvp.presenter.OrdersYiWanChengPresenter;
import com.xiaoxing.yunshu.mvp.ui.adapter.OrdersYiWanChengAdapter;
import com.xiaoxing.yunshu.mvp.ui.entity.OrdersYiWanCheng;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class OrdersYiWanChengFragment extends BaseFragment<OrdersYiWanChengPresenter> implements OrdersYiWanChengContract.View, OnRefreshListener, OnLoadMoreListener {


    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    private OrdersYiWanChengAdapter mAdapter;
    private List<OrdersYiWanCheng.DataBean> mDataBeanList = new ArrayList<>();
    private int mStart = 1;
    private int mNum = 10;

    public static OrdersYiWanChengFragment newInstance() {
        OrdersYiWanChengFragment fragment = new OrdersYiWanChengFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerOrdersYiWanChengComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .ordersYiWanChengModule(new OrdersYiWanChengModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_orders_yi_wan_cheng, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);

        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, 10, Color.parseColor("#EEEEEE")));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new OrdersYiWanChengAdapter(getActivity(), mDataBeanList ));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("grabNo", mDataBeanList.get(position).getGrabNo());
                Utils.navigation(getActivity(), RouterHub.ACTIVITY_YI_WAN_CHENG_XIANG_QING, bundle);
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据下拉刷新");
    }

    private List<OrdersYiWanCheng.DataBean> loadModels() {
        List<OrdersYiWanCheng.DataBean> lists = new ArrayList<>();

        for (int i = 0; i < 5; i++) {

            OrdersYiWanCheng.DataBean dataBean = new OrdersYiWanCheng.DataBean();
            lists.add(dataBean);
        }

        return lists;
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void getOrdersYiWanChengDataSuccess(OrdersYiWanCheng entityData) {
        if (entityData.getData() != null && entityData.getData().size() > 0) {

            mDataBeanList.clear();
            mDataBeanList.addAll(entityData.getData());

            mAdapter.notifyDataSetChanged();
            mStart += entityData.getData().size();

            mRecyclerView.setVisibility(View.VISIBLE);
            mEmptyLayout.setVisibility(View.GONE);
        } else {
            mRecyclerView.setVisibility(View.GONE);
            mEmptyLayout.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mStart = 1;

        getOrdersYiWanChengData();
        mRefreshLayout.finishRefresh();


    }

    private void getOrdersYiWanChengData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("startIndex", String.valueOf(mStart));
        map.put("endIndex", String.valueOf(mStart + mNum - 1));
        mPresenter.getOrdersYiWanChengData(map);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getOrdersYiWanChengData();
        mRefreshLayout.finishLoadMore();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }
}
